<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

function otx_validate_is_empty($value)
{
	$value = trim($value);
	return empty($value);
}

function otx_validate_not_empty($value)
{
	return !otx_validate_is_empty($value);
}

function otx_validate_is_email($value)
{
	$pattern = '/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/';
	return otx_validate_regex_match($pattern, $value);
}

function otx_validate_is_url($value)
{
	$pattern = '/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i';
	return otx_validate_regex_match($pattern, $value);
}

function otx_validate_regex_match($pattern, $value)
{
	return preg_match($pattern, $value);
}

function otx_validate_field_count($table_name, $field_name, $value, $where = '')
{
	$sql = 'SELECT COUNT(1) FROM ' . $table_name .
			' WHERE ' . otx_db_escape_identifier($field_name) . ' = ?' .
			(!empty($where) ? ' AND ' . otx_db_where($where) : '');
	return otx_db_fetch_one($sql, $value);
}

function otx_validate_field_exists($table_name, $field_name, $value, $where = '')
{
	$count = otx_validate_field_count($table_name, $field_name, $value, $where);
	return $count > 0;
}

function otx_validate_field_unique($table_name, $field_name, $value, $where = '')
{
	$count = otx_validate_field_count($table_name, $field_name, $value, $where);
	return $count == 1;
}